package com.caiya.controller;

import com.caiya.cart.Res;
import com.caiya.cart.entity.CartUser;
import com.caiya.mapper.CartUserMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.Example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;

/**
 * Created by Administrator on 2019/3/26 0026.
 */
@RestController
@Api(description = "user")
@RequestMapping("/user")
public class UserController {
    @Autowired
    private CartUserMapper cartUserMapper;

    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    @GetMapping(value = "/{id}")
    @ApiOperation(value = "id",notes = "id")
    public Res findById(@PathVariable("id")Long id){
        Res res = null;
        try {
            Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

            if (principal instanceof UserDetails){
                UserDetails user = (UserDetails)principal;
                Collection<? extends GrantedAuthority> collection = user.getAuthorities();

                for (GrantedAuthority c:collection){
                    UserController.LOGGER.info("当前用户是：{}，角色是：{}",user.getUsername(),c.getAuthority());
                }
            }else {
                UserController.LOGGER.info("当前用户是：{}，角色是：{}","错误","错误");
            }
            tk.mybatis.mapper.entity.Example example = new tk.mybatis.mapper.entity.Example(CartUser.class);
            tk.mybatis.mapper.entity.Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("id",id);
            CartUser cartUser = this.cartUserMapper.selectOneByExample(example);
            res = new Res(cartUser);
        }catch (Exception e){
            e.printStackTrace();
            res = new Res(Res.CODE_FAIL,e.getMessage());
        }
        return res;
    }
}
